package com.agentframework.core.plan;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.Message;

import java.util.List;
import java.util.Scanner;

import static com.agentframework.core.agent.Agent.MSG_FROM;

/**
 * @author wangjun
 **/
public class AskReview {

    protected static final Logger logger = LoggerFactory.getLogger(AskReview.class);
    private final List<Message> context;
    private final Plan plan;
    private final String trigger;

    public AskReview(List<Message> context, Plan plan, String trigger) {
        this.context = context;
        this.plan = plan;
        this.trigger = trigger;
    }

    public Planner.AskReviewResult execute() {
        if (plan != null) {
            for (Task task : plan.getTasks()) {
                logger.debug("{}: {}, is_finished: {}", task.getTaskId(), task.getInstruction(), task.getFinished());
            }
        }

        String prompt = getPrompt();
        logger.debug(prompt);

        Scanner scanner = new Scanner(System.in);
        String rsp = scanner.nextLine().trim();

        if (ReviewConst.EXIT_WORDS.contains(rsp.toLowerCase())) {
            scanner.close();
            System.exit(0);
        }

        boolean confirmed = ReviewConst.CONTINUE_WORDS.contains(rsp.toLowerCase()) ||
                rsp.toLowerCase().contains(ReviewConst.CONTINUE_WORDS.get(0));

        scanner.close();
        return new Planner.AskReviewResult(rsp, confirmed);
    }

    private String getPrompt() {
        String latestAction = (context != null && !context.isEmpty() && (context.get(context.size() - 1)).getMetadata().get(MSG_FROM) != null)
                ? (context.get(context.size() - 1)).getMetadata().get(MSG_FROM).toString()
                : "";

        String reviewInstruction = ReviewConst.TASK_REVIEW_INSTRUCTION;

        String prompt = String.format(
                "This is a <%s> review. Please review output from %s%n%s%n%s%nPlease type your review below:%n",
                trigger, latestAction, reviewInstruction, ReviewConst.EXIT_INSTRUCTION
        );
        return prompt;
    }

}
